#!/usr/bin/env python
# coding=utf-8
# __author__ = 'Yunchao Ling'

import sys
import ConfigParser
import time
import os


def checkSpace(dev):
    import commands
    import re

    space = 10
    line = commands.getoutput("df -B G -P")
    splitline = line.split("\n")
    for item in splitline:
        if item.startswith(dev):
            item = item.rstrip()
            regex = "^.*? *\d*G *\d*G *(\d*)G *\d*% *.*$"
            match = re.match(regex, item)
            if match:
                result = match.group(1)
                space = int(result)
                break
    return space


def countProcess():
    count = 0
    for line in os.popen("ps xa"):
        line = line.rstrip()
        if line.find("sh pmc_ftp.sh") != -1:
            count += 1
    return count


if __name__ == "__main__":
    config = ConfigParser.ConfigParser()
    config.read(sys.argv[1])
    dev = config.get("node", "dev")

    start = int(sys.argv[2], 16)
    end = int(sys.argv[3], 16)

    current_worklist = start
    while current_worklist <= end:
        if checkSpace(dev)>=2 and countProcess()==0:
            current_str = "{0:0>4x}".format(current_worklist)
            os.system("sh pmc_ftp.sh " + current_str[0:2] + " " + current_str[-2:] + " &")
            current_worklist += 1
        time.sleep(10)
